package com.myBlast.server;

import java.io.File;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.myBlast.data.BlastResult;
import com.utilities.IO.FileUtilities;

public class FileServlet extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req , HttpServletResponse resp)
	{
		boolean success = true;
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(req);
			Iterator iter = items.iterator();
			List<BlastResult> hitResults = null;
			File savedFile = null;
			File fullFile = null;
			String projectFolderName = null;
			
			// fetch the file
			if (iter.hasNext()) 
			{
			    FileItem item = (FileItem) iter.next();
			    String fieldName = item.getFieldName();
			    if (fieldName != null && fieldName.equalsIgnoreCase("fileUploadValue"))
			    {
			    	fullFile  = new File(item.getName());
			    	System.out.println("reading back the files");
					ObjectInputStream inputStream = new ObjectInputStream(item.getInputStream());
					hitResults = (ArrayList<BlastResult>)inputStream.readObject();
					inputStream.close();
			    }
			    else
			    {
			    	success = false;
			    	System.out.println("fieldName is not proper " + fieldName);
			    }
			}
			else 
			{
				success = false;
				System.out.println("No item present in request");
			}
			if (success)
			{
				// get the project folder Name
				BlastResult blastResult = hitResults.get(hitResults.size() - 1);
				projectFolderName = blastResult.getOrganismName();
				// if project folder Name is not present then make one and update the hitResults
				if (projectFolderName == null)
				{
					projectFolderName = makeProjectFolder(hitResults);
					savedFile = new File(MyBlastServiceImpl.ProjectFolder + "/" + projectFolderName);
				}
				// if it is there then check if the folder actually exists or not
				else
				{
					savedFile = new File(MyBlastServiceImpl.ProjectFolder + "/" + projectFolderName);
					// if the folder doesn't exists then make a new one and update the hitResults
					if (!(savedFile.exists() && savedFile.isDirectory()))
					{
						projectFolderName = makeProjectFolder(hitResults);
						savedFile = new File(MyBlastServiceImpl.ProjectFolder + "/" + projectFolderName);
					}
					// if the folder exists
					else
					{
						// remove the contents of the folder recursively
						if (savedFile.isDirectory())
						success = FileUtilities.cleanFolderRecursively(savedFile.getAbsolutePath(),false);
						// if it is a file then delete it and make a directory
						else
						{
							success = savedFile.delete();
							if (success) success = savedFile.mkdir();
						}
					}
					System.out.println("saved folder is " + savedFile.getAbsolutePath());
					// write the project settings and csv file in the project 
					if (success)
					{
						String fileNameWithoutExt = FileUtilities.removeExtension(savedFile.getAbsolutePath() 
								+ "/" + fullFile.getName().split("[.]")[0]);
						System.out.println("saved file is " + fileNameWithoutExt);
						success = BlastUtilitiies.writeProject(new ArrayList<BlastResult>(hitResults), fileNameWithoutExt);
					}
				}
			}
			PrintWriter pw = new PrintWriter(resp.getOutputStream());
			if (success)
			{
				pw.write(projectFolderName);
//				pw.write("parit");
			}
			else
				pw.write("no");
			pw.flush();
			pw.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

	private String makeProjectFolder(List<BlastResult> hitResults) 
	{
		String projectFolderName = FileUtilities.findFileWithUniqueName(MyBlastServiceImpl.ProjectFolder , null);
		BlastResult blastResult = hitResults.remove(hitResults.size() - 1); 
		blastResult.setOrganismName(projectFolderName);
		hitResults.add(blastResult);
		return projectFolderName;
	}
}

